﻿using Newtonsoft.Json;

namespace Gateway.Common.Extensions
{
    /// <summary>
    /// json格式化
    /// </summary>
    public static class JsonExtension
    {
        /// <summary>
        /// 将对象转化为json
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson (this object obj)
        {
            if (obj == null) return "";
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 将字符串转化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T ToModel<T>(this string value)
        {
            if(string.IsNullOrWhiteSpace(value)) return default(T);

            try
            {
                return JsonConvert.DeserializeObject<T>(value);
            }
            catch (Exception)
            {
                return default(T);
            }
        }
    }
}
